package com.cloud.user.controller;

import com.cloud.user.entity.UserInfo;
import com.cloud.user.service.UserInfoServiceInf;
import com.cloud.user.util.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *describe: 
 *
 *@author zhanghaixuan
 *@date 2018/10/06
 **/
@RestController
@RequestMapping("/login")
public class UserInfoController {
	private final static String BUYER = "1";

	private final static String SELLER = "2";

	@Autowired
	private UserInfoServiceInf userInfoServiceInf;

	@Autowired
	private StringRedisTemplate redisTemplate;

	@GetMapping("/buyer")
	public ResponseEntity buyer(@RequestParam("openid") String openid,
			HttpServletResponse response){
		UserInfo byOpenid = userInfoServiceInf.findByOpenid(openid);

		if(byOpenid == null){
			return ResponseEntity.status(500).body("用户名或者密码错误");
		}

		if(!BUYER.equals(byOpenid.getRole())){
			return ResponseEntity.status(500).body("角色错误");
		}

		CookieUtil.set(response,"openId",byOpenid.getOpenid(),7200);
		return ResponseEntity.ok("");
	}

	@GetMapping("/seller")
	public ResponseEntity seller(@RequestParam("openid") String openid,
			HttpServletRequest request,
			HttpServletResponse response){
		Cookie token1 = CookieUtil.get(request, "token");
		if(token1 != null && StringUtils.isNotEmpty(redisTemplate.opsForValue().get(String.format("token_",token1)))){
			return ResponseEntity.ok("");
		}

		UserInfo byOpenid = userInfoServiceInf.findByOpenid(openid);

		if(byOpenid == null){
			return ResponseEntity.status(500).body("用户名或者密码错误");
		}

		if(!SELLER.equals(byOpenid.getRole())){
			return ResponseEntity.status(500).body("角色错误");
		}
		String token = UUID.randomUUID().toString();
		redisTemplate.opsForValue().set(String.format("token_",token),byOpenid.getOpenid(),7200,TimeUnit.SECONDS);

		CookieUtil.set(response,"token",token,7200);
		return ResponseEntity.ok("");
	}
}
